import axios from 'axios'

axios.defaults.baseURL = ''
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 60000
axios.interceptors.request.use(
  (config) => {
    if (config.data instanceof FormData) {
      config.headers = {
        'Content-Type': 'multipart/form-data',
      }
    } else {
      config.data = JSON.stringify(config.data)
      config.headers = {
        'Content-Type': 'application/json',
      }
    }
    // config.headers.Authorization = "Bearer " + getToken();
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)
axios.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    if (!error.response) {
      return Promise.resolve({ code: 0, msg: '系统异常' })
    }
    if (error.response.status === 404) {
      return Promise.resolve({ code: 0, msg: '服务器错误,资源地址404' })
    }
    if (error.response.status === 504) {
      return Promise.resolve({ code: 0, msg: '网关超时504!' })
    }
    if (error.response.status === 403 || error.response.status === 401) {
      // window.location.href = '/'
    } else if (error.response.status === 429) {
      return Promise.resolve({ code: 0, msg: '请不要频繁刷新页面!' })
    } else {
      return Promise.resolve({
        code: 0,
        msg: `发生错误,状态码${error.response.status}`,
      })
    }
  },
)
export default axios
